package com.cqrt.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.dto.PlanCountDto;
import com.cqrt.dto.PlanMilestoneDTO;
import com.cqrt.entity.AuthorityManagementDO;
import com.cqrt.mapper.*;
import com.cqrt.service.ProjectBoardService;
import com.cqrt.util.PageDtoUtil;
import com.cqrt.vo.RTProjectBoardVO;
import com.cqrt.vo.SubJobVO;
import com.hustcad.plm.pdm.core.base.EntityBase;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.hustcad.plm.rpm.model.dto.active.TyppmActiveTreeDTO;
import com.hustcad.plm.rpm.model.dto.job.TyppmJobDTO;
import com.hustcad.plm.rpm.model.dto.team.ProjectTeamTreeDTO;
import com.hustcad.plm.rpm.model.dto.team.TyppmTeamTreeDTO;
import com.hustcad.plm.rpm.model.entity.admin.TyppmProject;
import com.hustcad.plm.rpm.service.plan.TyppmPlanActiveService;
import com.hustcad.plm.rpm.service.team.TyppmProjectTeamService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.vo.AttributeVO;
import com.ty.basic.vo.TyAttributeDefMapVO;
import com.ty.ppm.api.service.job.JobService;
import com.ty.ppm.model.dto.admin.ProjectDTO;
import com.ty.ppm.model.entity.job.Job;
import com.ty.ppm.model.entity.plan.PlanActive;
import com.ty.ppm.service.mapper.admin.PpmProjectMapper;
import dm.jdbc.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author：lotus
 * @DATE: 2025/7/11 21:58
 */

@Service
public class ProjectBoardServiceImpl implements ProjectBoardService {

    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyppmPlanActiveService typpmPlanActiveService;
    @Resource
    private RTProjectBoardMapper rtProjectBoardMapper;
    @Resource
    private BaseLinePlanExpandMapper baseLinePlanExpandMapper;
    @Resource
    private TyppmProjectTeamService typpmProjectTeamService;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private JobService jobService;
    @Resource
    private AuthorityManagementMapper authorityManagementMapper;
    @Resource
    private PpmProjectMapper ppmProjectMapper;
    @Resource
    RtWorkItemMapper rtWorkItemMapper;

    @Resource
    private RTTaskMapper rtTaskMapper;

    @Resource
    private RTProjectMapper rtProjectMapper;

    @Resource
    private RTOutRuleMapper rtOutRuleMapper;

    @Resource
    private RTTaskMapper taskMapper;

    @Override
    public PageDtoUtil queryProjectPageByCurrentUser(Integer pageNum, Integer pageSize) {


        List<RTProjectBoardVO> projectEntityVOList = getAllProjectList();
        UserDO user = TyAccountContext.getUser();
        Map<BigInteger,RTProjectBoardVO> projectEntityVOMap  = projectEntityVOList.stream().collect(Collectors.toMap(RTProjectBoardVO::getOid,item -> item));

        List<BigInteger> projectOidList = projectEntityVOList.stream().map(RTProjectBoardVO::getOid).collect(Collectors.toList());

        List<String> ibaAttr = Arrays.asList("ProjectDevelopmentOrder","SBR","Grade");
        Map<String, List<AttributeVO>> ibaAttrMapAll = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(
                projectOidList,
                TableTypeConstrant.TY_PROJECT_TYPE,
                ibaAttr);
        List<AuthorityManagementDO> authorityManagementDOList = authorityManagementMapper.selectAuthorityByUid(user.getOid());

        //获取项目经理为我的//存储最终返回值
        List<RTProjectBoardVO> result = projectEntityVOList.stream().filter(
                dos -> StringUtil.isNotEmpty(dos.getProjectManager()) && dos.getProjectManager().contains(user.getFullname())).collect(Collectors.toList());

        RTProjectBoardVO :
        for (RTProjectBoardVO projectEntityVO : projectEntityVOList) {

            String projectOid = String.valueOf(projectEntityVO.getOid());

            if(ibaAttrMapAll.containsKey(projectOid)) {
                List<AttributeVO> attributeVOS = ibaAttrMapAll.get(projectOid);
                if (CollectionUtils.isNotEmpty(attributeVOS)) {
                    Map<Object, AttributeVO> ibaAttrMap = attributeVOS.stream().collect(
                            Collectors.toMap(AttributeVO::getAttributeEnName, item -> item));
                    String category = projectEntityVO.getTypeDefName();
                    for (AuthorityManagementDO authorityManagementDO : authorityManagementDOList) {

                        //上报人是我
                        if (ibaAttrMap.containsKey("SBR")
                                && StringUtil.isNotEmpty(projectEntityVO.getProjectManager())
                                && projectEntityVO.getProjectManager().contains(
                                ibaAttrMap.get("SBR").getAttributeValuex())) {
                            result.add(projectEntityVO);
                            continue RTProjectBoardVO;
                        }
                        //权限有该项目
                        String projectType = authorityManagementDO.getProjectType();
                        String projectDetail = authorityManagementDO.getProjectDetail();
                        String detailValue = authorityManagementDO.getDetailValue();
                        if (category.equals(projectType)
                                && ibaAttrMap.containsKey(projectDetail)
                                && ibaAttrMap.get(projectDetail).getAttributeValue().equals(detailValue)
                                && authorityManagementDO.getPermission().contains("查看权限")
                        ) {
                            result.add(projectEntityVO);
                            continue RTProjectBoardVO;
                        }
                    }
                }
            }
            List<ProjectTeamTreeDTO> retList = this.typpmProjectTeamService.queryContainerTeamByContainer(projectOid,TableTypeConstrant.TY_PROJECT_TYPE);

            //所长或者部长是我
            if (CollectionUtils.isNotEmpty(retList)) {
                Optional<TyppmTeamTreeDTO> matchedChild = retList.stream()
                        .filter(dto -> "所长".equals(dto.getName()) || "院长".equals(dto.getName()))
                        .map(ProjectTeamTreeDTO::getChildren)
                        .filter(CollUtil::isNotEmpty)
                        .flatMap(List::stream)
                        .filter(child -> user.getFullname().equals(child.getFullName()))
                        .findFirst();

                if (matchedChild.isPresent()) {
                    result.add(projectEntityVO);
                }
            }

        }

        //获取所有项目计划
        List<String> attrNameList = Arrays.asList("PersonCharge","RecoveryPlan","PostponedClassification","ReasonFor");
        Map<BigInteger, List<PlanActive>> projectStagePlans = rtProjectBoardMapper
                .selectStagePlansByIds(projectOidList)
                .stream()
                .collect(Collectors.groupingBy(PlanActive::getContaineroid));

        // 2. 筛选符合时间条件的阶段计划，批量查询jobId（按计划OID分组）
        LocalDateTime now = LocalDateTime.now();
        // 收集所有符合条件的计划OID
        List<BigInteger> qualifiedPlanOids = projectStagePlans.values().stream()
                .flatMap(Collection::stream)
                .filter(plan -> {
                    LocalDateTime earlyStart = plan.getEarlyStart();
                    LocalDateTime earlyFinish = plan.getEarlyFinish();
                    return earlyStart != null && earlyFinish != null
                            && earlyStart.isBefore(now)
                            && earlyFinish.isAfter(now);
                })
                .map(PlanActive::getOid)
                .collect(Collectors.toList());

        // 批量查询计划对应的jobId，按计划OID分组
        Map<BigInteger, BigInteger> planJobMap = rtProjectBoardMapper
                .selectJobsByIds(qualifiedPlanOids)  // 假设存在批量查询方法
                .stream()
                .collect(Collectors.toMap(
                        Job::getActivityID,  // 假设返回Map<计划OID, jobId>
                        Job::getOid
                ));

        List<BigInteger> jobIds = new ArrayList<>(planJobMap.values());
        Map<BigInteger, List<AttributeVO>> jobAttrMap = CollectionUtils.isEmpty(jobIds)
                ? Collections.emptyMap()
                : typlmAttributeValueService.getIbaAttrValueByOidAndKeys(jobIds, TableTypeConstrant.TY_JOB_OTYPE, attrNameList)
                .entrySet().stream()
                .collect(Collectors.toMap(
                        entry -> new BigInteger(entry.getKey()),
                        Map.Entry::getValue
                ));

        for (RTProjectBoardVO projectVO : result) {
            BigInteger projectOid = projectVO.getOid();
            if (projectOid == null) {
                continue;
            }

            // 获取当前项目的阶段计划
            List<PlanActive> stagePlans = projectStagePlans.getOrDefault(projectOid, Collections.emptyList());
            if (CollectionUtils.isEmpty(stagePlans)) {
                continue;
            }

            // 处理符合时间条件的计划
            stagePlans.stream()
                    .filter(plan -> {
                        LocalDateTime earlyStart = plan.getEarlyStart();
                        LocalDateTime earlyFinish = plan.getEarlyFinish();
                        return earlyStart != null && earlyFinish != null
                                && earlyStart.isBefore(now)
                                && earlyFinish.isAfter(now);
                    })
                    .findFirst()  // 假设只需要第一个符合条件的计划（可根据业务调整）
                    .ifPresent(qualifiedPlan -> {
                        projectVO.setPhasePlan(qualifiedPlan.getName());  // 计划名称
                        projectVO.setPhaseAccomplishDate(qualifiedPlan.getEarlyFinish());
                        // 获取计划对应的jobId
                        BigInteger jobId = planJobMap.get(qualifiedPlan.getOid());
                        if (jobId == null) {
                            return;
                        }

                        // 获取job的属性值并设置到VO
                        List<AttributeVO> attrs = jobAttrMap.getOrDefault(jobId, Collections.emptyList());
                        setProjectAttributes(projectVO, attrs);  // 提取属性设置逻辑
                    });
        }


        //给项目添加开发令字段
        List<String> projectNameList = Collections.singletonList("ProjectDevelopmentOrder");
        Map<String, List<AttributeVO>> ibaValue = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(projectOidList, TableTypeConstrant.TY_PROJECT_TYPE, projectNameList);
        for (String oid : ibaValue.keySet()) {
            RTProjectBoardVO projectEntityVO = projectEntityVOMap.get(new BigInteger(oid));
            if (ObjectUtil.isNotNull(projectEntityVO)) {
                projectEntityVO.setDevOrder(ibaValue.get(oid).get(0).getAttributeValue());
            }
        }

        result.sort(Comparator.comparing(RTProjectBoardVO::getCreateStamp).reversed());
        for (RTProjectBoardVO rtProjectBoardVO : result) {
            //获取二级项目任务
            String jobId = rtWorkItemMapper.selectPJJobIdByPJID(rtProjectBoardVO.getOid().toString());
            if (StringUtil.isNotEmpty(jobId)){
                //延期分类
                rtProjectBoardVO.setExtensionClassification(rtWorkItemMapper.queryExtendedAttributes(jobId,"PostponedClassification"));
                //挽回计划
                rtProjectBoardVO.setRecoveryPlan(rtWorkItemMapper.queryExtendedAttributes(jobId,"RecoveryPlan"));
                //责任人
                rtProjectBoardVO.setPersonCharge(rtWorkItemMapper.queryExtendedAttributes(jobId,"PersonCharge"));
            }

        }
        return PageDtoUtil.getPageDto(result,pageNum,pageSize);
    }

    @Override
    public List<TyppmActiveTreeDTO> getLevelOnePlanActiveTreePlan(String planOid) {

        String rootOTYPE = TableTypeConstrant.TY_PJ_PLAN_OTYPE;
        return this.getLevelOnePlanActiveTreeByPlan(planOid,rootOTYPE);
    }

    @Override
    public PageDtoUtil queryProjectTask(Integer pageNum, Integer pageSize) {
        List<TyppmJobDTO> result = new ArrayList<>();
        UserDO user = TyAccountContext.getUser();
        List<TyppmJobDTO> typpmJobs = rtProjectBoardMapper.queryNotJobByUserAndStatus(String.valueOf(user.getOid()));
        if(CollectionUtils.isNotEmpty(typpmJobs)){
            result.addAll(typpmJobs);
        }
        //获取所有项目
        List<TyppmProject> typpmProject = rtProjectBoardMapper.queryProject();
        List<BigInteger> projectOidList = typpmProject.stream().map(dto -> new BigInteger(dto.getOid())).collect(Collectors.toList());
        //存储有权限的项目id
        List<BigInteger> projectOidData = new ArrayList<>();
        //权限
        List<AuthorityManagementDO> authorityManagementDOList = authorityManagementMapper.selectAuthorityByUid(user.getOid());
        List<String> ProjectNameList = Arrays.asList("Grade");
        Map<String, List<AttributeVO>> projectValueAttrMap = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(projectOidList, TableTypeConstrant.TY_PROJECT_TYPE, ProjectNameList);

        for (TyppmProject project : typpmProject) {
            String projectOid = project.getOid();
            if(!projectValueAttrMap.containsKey(projectOid)){
                continue;
            }
            List<AttributeVO> attributeVOS = projectValueAttrMap.get(projectOid);
            if(CollectionUtils.isNotEmpty(attributeVOS)){
                Map<Object, AttributeVO> ibaAttrMap = attributeVOS.stream().collect(Collectors.toMap(AttributeVO::getAttributeEnName, item -> item));
                String category = project.getCategory();
                for (AuthorityManagementDO authorityManagementDO : authorityManagementDOList) {
                    String projectType = authorityManagementDO.getProjectType();
                    String projectDetail = authorityManagementDO.getProjectDetail();
                    String detailValue = authorityManagementDO.getDetailValue();
                    if(     category.equals(projectType)
                            && ibaAttrMap.containsKey(projectDetail)
                            && ibaAttrMap.get(projectDetail).getAttributeValue().equals(detailValue)
                            && authorityManagementDO.getPermission().contains("查看权限")
                    ){
                        projectOidData.add(new BigInteger(projectOid));
                    }
                }
            }
        }
        //根据项目ID查询任务 —-》 添加到result中
        if (CollectionUtils.isNotEmpty(projectOidData)) {
            List<TyppmJobDTO> typpm = rtProjectBoardMapper.queryNotJobByProjectOid(projectOidData, user.getOid());
            result.addAll(typpm);
        }

        //获取项目任务iba属性
        List<String> attrNameList = Arrays.asList("TaskProgress","DelayingMeasures");
        List<BigInteger> ppmJobOid = typpmJobs.stream().map(dto -> new BigInteger(dto.getOid())).collect(Collectors.toList());
        Map<String, List<AttributeVO>> ibaValueAttrMap = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(ppmJobOid, TableTypeConstrant.TY_JOB_OTYPE, attrNameList);

        //获取全路径
        List<String> ppmJobOidStr = result.stream().map(EntityBase::getOid).collect(Collectors.toList());
        Map<String, String> jobNamePathMap = this.jobService.queryJobNamePath(ppmJobOidStr);

        for (TyppmJobDTO typpmJobDTO : result) {
            String projectVOOid = typpmJobDTO.getOid();
            if (ibaValueAttrMap.containsKey(projectVOOid)) {
                List<AttributeVO> attributeVOS = ibaValueAttrMap.get(projectVOOid);
                if (CollUtil.isEmpty(attributeVOS)) {
                    continue;
                }
                for (AttributeVO attributeVO : attributeVOS) {
                    if ("TaskProgress".equals(attributeVO.getAttributeEnName())) {
                        typpmJobDTO.setTaskProgress(attributeVO.getAttributeValuex());
                    } else if ("DelayingMeasures".equals(attributeVO.getAttributeEnName())) {
                        typpmJobDTO.setDelayingMeasures(attributeVO.getAttributeValuex());
                    }
                }
            }
            typpmJobDTO.setExecutorDescription(user.getFullname());
            if(jobNamePathMap.containsKey(typpmJobDTO.getOid())){
                typpmJobDTO.setJobNamePath(jobNamePathMap.get(typpmJobDTO.getOid()));
            }
        }
        //排序
        result.sort(Comparator.comparing(TyppmJobDTO::getCreatestamp).reversed());

        return PageDtoUtil.getPageDto(result,pageNum,pageSize);
    }

    @Override
    public PageDtoUtil queryNotIssuedTask(Integer pageNum, Integer pageSize) {
        UserDO user = TyAccountContext.getUser();
        List<TyppmJobDTO> typpmJobs = rtProjectBoardMapper.queryJobByUserAndStatus(String.valueOf(user.getOid()));

        if (CollUtil.isEmpty(typpmJobs)) {
            throw RTErrorCodeEnum.PROJECT_ACTIVE_ERROR.getException("没有待下达的任务");
        }
        List<String> attrNameList = Arrays.asList("TaskProgress","DelayingMeasures");
        List<BigInteger> ppmJobOid = typpmJobs.stream().map(dto -> new BigInteger(dto.getOid())).collect(Collectors.toList());
        List<String> ppmJobOidStr = typpmJobs.stream().map(EntityBase::getOid).collect(Collectors.toList());
        Map<String, List<AttributeVO>> ibaValueAttrMap = typlmAttributeValueService.getIbaAttrValueByOidAndKeys(ppmJobOid, TableTypeConstrant.TY_JOB_OTYPE, attrNameList);
        Map<String, String> jobNamePathMap = this.jobService.queryJobNamePath(ppmJobOidStr);
        for (TyppmJobDTO typpmJobDTO : typpmJobs) {
            String projectVOOid = typpmJobDTO.getOid();
            if (ibaValueAttrMap.containsKey(projectVOOid)) {
                List<AttributeVO> attributeVOS = ibaValueAttrMap.get(projectVOOid);
                if (CollUtil.isEmpty(attributeVOS)) {
                    continue;
                }
                for (AttributeVO attributeVO : attributeVOS) {
                    if ("TaskProgress".equals(attributeVO.getAttributeEnName())) {
                        typpmJobDTO.setTaskProgress(attributeVO.getAttributeValuex());
                    } else if ("DelayingMeasures".equals(attributeVO.getAttributeEnName())) {
                        typpmJobDTO.setDelayingMeasures(attributeVO.getAttributeValuex());
                    }
                }
            }
            typpmJobDTO.setExecutorDescription(user.getFullname());
            if(jobNamePathMap.containsKey(typpmJobDTO.getOid())){
                typpmJobDTO.setJobNamePath(jobNamePathMap.get(typpmJobDTO.getOid()));
            }
        }
        typpmJobs.sort(Comparator.comparing(TyppmJobDTO::getCreatestamp).reversed());


        return PageDtoUtil.getPageDto(typpmJobs,pageNum,pageSize);
    }

    @Override
    //根据类型查出所有拓展属性
    public List<String> queryIbaName(String type) {

        BigInteger typeOid = rtProjectBoardMapper.queryTypeOidByName(type);
        if(typeOid == null){
            return Collections.emptyList();
        }
        List<TyAttributeDefMapVO> tyAttributeDefMapVOS = typlmTypeService.queryInheritAttrDef(typeOid, TableTypeConstrant.TY_TYPE_OTYPE);
        if(CollUtil.isNotEmpty(tyAttributeDefMapVOS)){
            return tyAttributeDefMapVOS.stream().map(TyAttributeDefMapVO::getName).collect(
                    Collectors.toList());
        }
        return Collections.emptyList();
    }

    @Override
    public PageDtoUtil checkProjectTask(TyppmJobDTO TyppmJobDTO,Integer pageNum, Integer pageSize) {

        /*PageDtoUtil pageDtoUtil = this.queryProjectTask(1,Integer.MAX_VALUE);

        List<TyppmJobDTO> typpmJobs = (List<TyppmJobDTO>)pageDtoUtil.getPageList();
        if (ObjectUtil.isEmpty(TyppmJobDTO)) {
            return PageDtoUtil.getPageDto(typpmJobs, pageNum, pageSize);
        }
        List<TyppmJobDTO> typlmWorkItemTaskVOS = this.filterPeople(typpmJobs, TyppmJobDTO);*/

        return PageDtoUtil.getPageDto(null, pageNum, pageSize);
    }

    @Override
    public PageDtoUtil queryTheWaitingProjectTasks(Integer pageNum, Integer pageSize) {
        UserDO user = TyAccountContext.getUser();
        List<TyppmJobDTO> typpmJobs = rtTaskMapper.queryWaitingProjectTasks(user.getOid());
        List<TyppmJobDTO> wait = new ArrayList<>();
        for (int j=typpmJobs.size()-1;j>=0;j--){
            TyppmJobDTO jobDTO = typpmJobs.get(j);
            if(jobDTO.getState().equals("未读")){
                //typpmJobs.remove(j);
            }
        }


        for (int i = 0; i < typpmJobs.size(); i++) {
            TyppmJobDTO jobDTO = typpmJobs.get(i);
            //任务路径名称
            jobDTO.setJobNamePath(getJobPathName(new BigInteger(jobDTO.getOid()),""));

            //执行状态
            String executedStatus = rtTaskMapper.selectExecutedStatus(jobDTO.getOid());
            jobDTO.setExStatus(executedStatus);
            //开发令
            BigInteger projectId = rtProjectMapper.selectProjectById(new BigInteger(jobDTO.getOid()));
            String pjName = rtProjectMapper.selectProjectNameByProjectOid(projectId.toString());
            //项目名
            jobDTO.setProjectName(pjName);
            jobDTO.setPlanName(pjName);
            if(StrUtil.isNotBlank(pjName)) {
                Map<String, String> stringStringMap = rtProjectMapper.selectDevelopmentOrderByProjectName(pjName);
                if (CollUtil.isNotEmpty(stringStringMap)) {
                    jobDTO.setProjectDevelopmentOrder(stringStringMap.get("PROJECT_CODE"));
                }
            }
            //延期分类
            jobDTO.setExtensionClassification(rtWorkItemMapper.queryExtendedAttributes(jobDTO.getOid(),"PostponedClassification"));
            //挽回计划
            jobDTO.setRecoveryPlan(rtWorkItemMapper.queryExtendedAttributes(jobDTO.getOid(),"RecoveryPlan"));
            //责任人
            jobDTO.setPersonCharge(rtWorkItemMapper.queryExtendedAttributes(jobDTO.getOid(),"PersonCharge"));
            String jobId = jobDTO.getOid().toString();
            //通过任务ID查询活动 ID
            BigInteger activityIdBigInteger = rtTaskMapper.selectActivityIdById(jobId);
            String activityId = "";
            if(activityIdBigInteger!=null){
                activityId = activityIdBigInteger.toString();
            }
            //通过活动ID查询前置任务的OID
            List<BigInteger> predecessorTaskOidBigIntegers = rtTaskMapper.selectBOidByAOid(activityId);
            //如果存在前置任务，且前置任务状态不是已完成，抛出异常
            if (CollUtil.isNotEmpty(predecessorTaskOidBigIntegers)) {
                for (BigInteger predecessorTaskOidBigInteger : predecessorTaskOidBigIntegers) {
                    String predecessorTaskOid = predecessorTaskOidBigInteger.toString();
                    String isComplete = rtTaskMapper.selectStateByActivityId(predecessorTaskOid);
                    if (!"已完成".equals(isComplete)) {
                        //waitList.add(jobDTO);
                        wait.add(jobDTO);
                    }
                }
            }
        }


        return PageDtoUtil.getPageDto(wait,pageNum,pageSize);
    }

    public String getJobPathName(BigInteger OID, String pathName) {
        //通过传过来的父OID查询父级任务
        TyppmJobDTO parentJob = rtProjectBoardMapper.selectParentJobs(OID);
        String parentJobName = parentJob.getName();
        if (parentJobName != null && parentJobName.length() > 0) {
            pathName = parentJobName + "/" + pathName;
        }
        if (parentJob.getParentNodeOid() != null) {
            pathName = getJobPathName(parentJob.getParentNodeOid(), pathName);
        }else {
            List<BigInteger> planOid=rtProjectBoardMapper.getPlanOid(new BigInteger(parentJob.getOid()));
            if(CollUtil.isNotEmpty(planOid)) {
                String planName = rtProjectBoardMapper.getPlanName(planOid.get(0));
                pathName = planName + "/" + pathName;
            }
        }
        return pathName;
    }

    public String getPlanName(BigInteger oid) {
        //根据计划OID获取计划名称
        String planName = rtProjectBoardMapper.getPlanName(oid);
        return planName;
    }



    //获取一级任务树
    public List<TyppmActiveTreeDTO> getLevelOnePlanActiveTreeByPlan(String planOid, String rootOTYPE) {
        Map<String, Object> params = new HashMap();
        params.put("rootOID", planOid);
        params.put("rootOTYPE", rootOTYPE);
        params.put("markfordelete", 0L);
        return this.typpmPlanActiveService.getLevelOnePlanActiveTreeByPlan(params);
    }


    //筛选list
    public  List<TyppmJobDTO> filterPeople(List<TyppmJobDTO> list,TyppmJobDTO vo) {
        // 动态构建 Predicate 组合
        Predicate<TyppmJobDTO> predicate = p -> true;  // 初始化为始终true

        // 任务标题
        if (vo.getName() != null && !vo.getName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getName() != null && p.getName().contains(vo.getName())
            );
        }
        // 状态
        if (vo.getState() != null && !vo.getState().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getState() != null && p.getState().contains(vo.getState())
            );
        }
        // 全路径
        if (vo.getJobNamePath() != null && !vo.getJobNamePath().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getJobNamePath() != null && p.getJobNamePath().contains(vo.getJobNamePath())
            );
        }
        // 所属项目
        if (vo.getProjectName() != null && !vo.getProjectName().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getProjectName() != null && p.getProjectName().contains(vo.getProjectName())
            );
        }// 截止日期
        if (vo.getFinishdate() != null) {
            predicate = predicate.and(p ->
                                              p.getFinishdate() != null && p.getFinishdate().toLocalDate().equals(vo.getFinishdate().toLocalDate())
            );
        }// 计划工时
        if (vo.getDurationmillis() != null) {
            predicate = predicate.and(p ->
                                              p.getDurationmillis() != null && Objects.equals(p.getDurationmillis(),
                                                                                              vo.getDurationmillis())
            );
        }// 实际工时
        if (vo.getDoneeffortmillis() != null) {
            predicate = predicate.and(p ->
                                              p.getDoneeffortmillis()  != null && Objects.equals(
                                                      p.getDoneeffortmillis(), vo.getDoneeffortmillis())
            );
        }// 负责人
        if (vo.getExecutorDescription() != null && !vo.getExecutorDescription().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getExecutorDescription() != null && p.getExecutorDescription().contains(vo.getExecutorDescription())
            );
        }// 创建时间
        if (vo.getCreatestamp() != null) {
            predicate = predicate.and(p ->
                                              p.getCreatestamp() != null && p.getCreatestamp()
                                                      .toLocalDate().equals(vo.getCreatestamp().toLocalDate())
            );
        }// 延期对策
        if (vo.getDelayingMeasures() != null && !vo.getDelayingMeasures().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getDelayingMeasures() != null && p.getDelayingMeasures().contains(vo.getDelayingMeasures())
            );
        }
        // 任务进度说明
        if (vo.getTaskProgress() != null && !vo.getTaskProgress().trim().isEmpty()) {
            predicate = predicate.and(p ->
                                              p.getTaskProgress() != null && p.getTaskProgress().contains(vo.getTaskProgress())
            );
        }

        // 应用筛选条件
        return list.stream()
                .filter(predicate)
                .collect(Collectors.toList());
    }


    //查询所有项目
    public List<RTProjectBoardVO> getAllProjectList() {

        List<RTProjectBoardVO> rtProjectBoardVOList = rtProjectBoardMapper.queryAllProject();

        List<BigInteger> projectOidList = rtProjectBoardVOList.stream().map(RTProjectBoardVO::getOid).collect(Collectors.toList());
        List<ProjectDTO> projectManager = ppmProjectMapper.getProjectManager(projectOidList);
        Map<BigInteger, ProjectDTO> projectManagerMap = projectManager.stream().collect(Collectors.toMap(
                CTyEntityBaseDO::getOid, d -> d));
        List<PlanCountDto> planCountDtos = rtProjectBoardMapper.queryProjectCountJob(projectOidList);
        Map<BigInteger, BigDecimal> planCountDtosMap = planCountDtos.stream().collect(
                Collectors.toMap(PlanCountDto::getOid, PlanCountDto::getPlanCount,
                                 (existing, replacement) -> existing));

        List<PlanMilestoneDTO> planMilestoneDTOS = rtProjectBoardMapper.queryPlanByMilestone(projectOidList);
        Map<BigInteger, String> planMilestoneDTOMap = planMilestoneDTOS.stream()
                .collect(Collectors.toMap(
                        PlanMilestoneDTO::getPeojectbyoid,
                        PlanMilestoneDTO::getName,
                        (existing, replacement) -> existing
                ));

        LocalDateTime currentDateTime = LocalDateTime.now();
        for (RTProjectBoardVO rtProjectBoardVO : rtProjectBoardVOList) {

             //剩余天数
            Duration duration = Duration.between(currentDateTime, rtProjectBoardVO.getFinishDate());
            rtProjectBoardVO.setFinishDateDeff(BigInteger.valueOf(duration.toDays()));

            //项目经理
            ProjectDTO projectDTO = projectManagerMap.get(rtProjectBoardVO.getOid());
            if (ObjectUtil.isNotEmpty(projectDTO)) {
                rtProjectBoardVO.setProjectManager(projectDTO.getAdministratorsName());
            }
            //进度
            if (planCountDtosMap.containsKey(rtProjectBoardVO.getOid())) {
                rtProjectBoardVO.setPercentWorkComplete(planCountDtosMap.get(rtProjectBoardVO.getOid()));
            }
            //里程碑
            if (planMilestoneDTOMap.containsKey(rtProjectBoardVO.getOid())) {
                rtProjectBoardVO.setCurMileStoneName(planMilestoneDTOMap.get(rtProjectBoardVO.getOid()));
            }

        }
        return rtProjectBoardVOList;
    }


    private void setProjectAttributes(RTProjectBoardVO projectVO, List<AttributeVO> attrs) {
        if (CollectionUtils.isEmpty(attrs)) {
            return;
        }
        // 用Map存储属性英文名到设置逻辑的映射，简化条件判断
        Map<String, Consumer<AttributeVO>> attrSetterMap = new HashMap<>();
        attrSetterMap.put("PersonCharge", attr -> projectVO.setPersonCharge(attr.getAttributeValue()));
        attrSetterMap.put("RecoveryPlan", attr -> projectVO.setRecoveryPlan(attr.getAttributeValue()));
        attrSetterMap.put("PostponedClassification", attr -> projectVO.setExtensionClassification(attr.getAttributeValue()));
        attrSetterMap.put("ReasonFor", attr -> projectVO.setReasonPostponement(attr.getAttributeValue()));

        // 遍历属性并设置
        attrs.forEach(attr -> {
            String attrEnName = attr.getAttributeEnName();
            if (attrSetterMap.containsKey(attrEnName)) {
                attrSetterMap.get(attrEnName).accept(attr);  // 执行对应设置逻辑
            }
        });
    }

}

